package ru.jexp.rcp.supply.actions;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;

public class ActionMenuCreator implements IMenuCreator {

	private List<IAction> actions = new ArrayList<IAction>();
	private Menu dropDown;
	private Menu popUp;

	public void addAction(IAction action) {
		actions.add(action);
	}

	@Override
	public void dispose() {
		if (dropDown != null && !dropDown.isDisposed()) {
			dropDown.dispose();
			dropDown = null;
		}
		if (popUp != null && !popUp.isDisposed())
		{
			popUp.dispose();
			popUp = null;
		}
	}

	@Override
	public Menu getMenu(Control parent) {
		if (dropDown == null) {
			Menu menu = new Menu(parent);
			for (IAction item : actions) {
				ActionContributionItem aci = new ActionContributionItem(item);
				aci.fill(menu, menu.getItemCount());
			}
			dropDown = menu;
		}
		return dropDown;
	}

	@Override
	public Menu getMenu(Menu parent) {
		if (popUp == null) {
			Menu menu = new Menu(parent);
			for (IAction item : actions) {
				ActionContributionItem aci = new ActionContributionItem(item);
				aci.fill(menu, menu.getItemCount());
			}
			popUp = menu;
		}
		return popUp;
	}

}
